package org.akomantoso.core.io.util;

import java.io.IOException;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.AmendmentsElement;
import org.akomantoso.core.data.MeaningMod;
import org.akomantoso.core.data.ScopeMod;
import org.akomantoso.core.data.TextualMod;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;

/**
 * 
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 * 
 */
public class AmendmentsElementUtil {

	private AmendmentsElementUtil() {
	}

	static final Map<String, Instantiator<AmendmentsElement>> MAP;

	public static void read(Input in, List<AmendmentsElement> elements) throws IOException {

		AmendmentsElement element = null;
		final String localName = in.getLocalName();
		int eventType;

		while (true) {
			eventType = in.readNext();

			if (InputConstants.START_ELEMENT == eventType) {
				elements.add(element = instantiate(in.getLocalName()));
				element.readExternal(in);
			}

			if (InputConstants.END_ELEMENT == eventType && localName.equals(in.getLocalName())) {
				return;
			}

		}
	}

	static AmendmentsElement instantiate(String elementName) {

		final Instantiator<AmendmentsElement> instatiator = MAP.get(elementName);
		if (instatiator == null) {
			throw new RuntimeException("Tag [" + elementName + "] not supported for AmendmentsElement ?!?");
		}
		return instatiator.instantiate();

	}

	static {

		Map<String, Instantiator<AmendmentsElement>> temp = new IdentityHashMap<String, Instantiator<AmendmentsElement>>();

		// textualMod
		temp.put(TextualMod.ELEMENT, new Instantiator<AmendmentsElement>() {
			public TextualMod instantiate() {
				return new TextualMod();
			}
		});

		// meaningMod
		temp.put(MeaningMod.ELEMENT, new Instantiator<AmendmentsElement>() {
			public MeaningMod instantiate() {
				return new MeaningMod();
			}
		});
		

		// scopeMod
		temp.put(ScopeMod.ELEMENT, new Instantiator<AmendmentsElement>() {
			public ScopeMod instantiate() {
				return new ScopeMod();
			}
		});

		MAP = temp;

	}
}